import React, { Component } from "react";
import { prefixFile, workOrderList, faultTypeList, erpUserList, returnVisit, updateCallTimes } from "../../../fetch/fetchApi";
import GridTable from '../../../components/display/gridTable';
import { Button, Input, Row, Col, Select, Divider, Modal, Form, Tooltip, Upload, Icon, Progress, DatePicker, message, Spin, Dropdown, Menu } from 'antd';
import locale from "antd/lib/date-picker/locale/zh_CN";
import AreaPicker from '../../../components/dataEntry/areaPicker';
import ReturnVisit from './returnVisit';

const Option = Select.Option;
const {TextArea} = Input;
const {RangePicker} = DatePicker;

let isInitPagination = false;
class ManageWorkOrder extends Component {

    constructor(props) {
        super(props);
        this.init();
        this.state = {
            data: [],
            pagination: {}
        };
    }

    componentDidMount() {
        this.fetch();
    }

    combineTypeOptions = (code, optionsName) => {
        faultTypeList({
            code: code
        }).then((res) => {
            if (!res) {
                return;
            }
            let options = [];
            if (res.data.code === "200") {
                const typeArr = res.data.data;
                for (let item in typeArr) {
                    options.push(<Option value={typeArr[item].c_id} key={typeArr[item].c_id}>{typeArr[item].c_name}</Option>);
                }
            }
            this.setState({
                [optionsName]: options
            })
        })
    }

    combineUserOptions=(role, optionsName) => {
        erpUserList({
            role: role
        }).then((res) => {
            if (!res) {
                return;
            }
            let options = [];
            if (res.data.code === "200") {
                const list = res.data.data.list;
                for ( let item of list ) {
                    options.push(<Option value={item.id} key={item.id}>{item.name}</Option>);
                }
            }
            this.setState({
                [optionsName]: options
            })
        })
    }

    init() {
        this.query = {
            page: 1,
            pagecount: 10
        };
        this.returnVisitParams = {};
        this.currentRecordId = "";

        this.tableColumns = [
            {
                title: '工单编号',
                dataIndex: 'workOrderNo',
                fixed: 'left',
                width: 100
            }, {
                title: '电桩编号',
                dataIndex: 'stubNo'
            }, {
                title: '电站名称',
                dataIndex: 'stubGroupName'
            }, {
                title: '型号',
                dataIndex: 'stubModel'
            }, {
                title: '故障代码',
                dataIndex: 'codeStr'
            }, {
                title: '故障类型',
                dataIndex: 'typeStr'
            }, {
                title: '优先级',
                dataIndex: 'priorityStr'
            }, {
                title: '故障描述',
                dataIndex: 'faultDesc',
                render: (text, record) => (
                    <div>
						<Tooltip placement="topLeft" title={text} >
	                        {text ? (text.length > 20 ? text.substring(0, 20) + "..." : text) : text}
	                	</Tooltip>
                	</div>
                )
            }, {
                title: '报修人',
                dataIndex: 'userName'
            }, {
                title: '联系电话',
                dataIndex: 'userPhone'
            }, {
                title: '报修次数',
                dataIndex: 'repairTimes'
            }, {
                title: '来电次数',
                dataIndex: 'callTimes',
                render: (text, record) => (
                    <div>
						<Tooltip placement="topLeft" title={text} >
	                        {text ? text : 0}
	                	</Tooltip>
                	</div>
                )
            }, {
                title: '工单状态',
                dataIndex: 'statusStr'
            }, {
                title: '创建人',
                dataIndex: 'creatorStr'
            }, {
                title: '创建时间',
                dataIndex: 'createTime',
                render: (text, record) => (
                    <div>
						{text ? text.split(".")[0] : "--"}
                	</div>
                )
            }, {
                title: '维修站',
                dataIndex: 'siteStr'
            }, {
                title: '维修人',
                dataIndex: 'fixManStr'
            }, {
                title: '客服',
                dataIndex: 'csStr'
            }, {
                title: '城市',
                dataIndex: 'city',
                render: (text, record) => (
                    <div>
						{record.provinceStr ? `${record.provinceStr}-${record.cityStr}` : "--"}
                	</div>
                )
            }, {
                title: '维修响应时间',
                dataIndex: 'wopTime',
                render: (text, record) => (
                    <div>
						{text ? text.split(".")[0] : "--"}
                	</div>
                )
            }, {
                title: '操作',
                key: 'operation',
                fixed: 'right',
                render: (text, record) => (
                this.getOperation(record)
                )
            }
        ];
        // 故障类别
        this.combineTypeOptions("351", "typeOptions");
        // 工单状态
        this.combineTypeOptions("412", "statusOptions");
        // 客服
        this.combineUserOptions("1953", "csOptions");
        // 维修人
        this.combineUserOptions("1729", "repairManOptions");
    }

    getOperation(record) {
        let dom;
        switch (record.workOrderStatus) {
        //待处理
        case "423":
            dom = <a href="javascript:void(0);" onClick={(e) => this.handleCallBtnClick(record)}>来电</a>
            break;
        //已派工
        case "424":
            dom = <a href="javascript:void(0);" onClick={(e) => this.handleCallBtnClick(record)}>来电</a>
            break;
        //已完结
        case "1951":
            dom = <a href="javascript:void(0);" onClick={(e) => this.handleReturnVisitBtnClick(record)}>回访</a>
            break;
        default:
            dom = <p>--</p>
        }
        return dom;
    }

    handleCallBtnClick=(record) => {
        updateCallTimes({
            id: record.key,
            callTimes: record.callTimes ? (parseInt(record.callTimes) + 1) : 1
        }).then((res) => {
            if (!res) {
                return;
            }
            if (res.data.code === "200") {
                message.success("操作成功！");
            }
        })
    }

    handleReturnVisitBtnClick=(record) => {
        this.currentRecordId = record.key;
        this.setState({
            returnVisitModalVisible: true,
            record: record
        })
    }

    queryHandler = () => {
        this.query["page"] = 1;
        this.fetch();
    }

    fetch = (params = {}) => {
        this.setState({
            loading: true
        });
        workOrderList(this.query).then((res) => {
            if (!res) {
                return;
            }
            const pagination = this.state.pagination;
            pagination.total = res.data.data.totalCount;
            pagination.current = params.current || 1;

            pagination.onChange = (page, pageSize) => {
                this.query["page"] = page;
                this.query["pagecount"] = pageSize;
                this.fetch({
                    current: page
                });
            }
            let dataSource = res.data.data.list;
            this.setState({
                loading: false,
                data: dataSource,
                pagination
            });
        }).catch((ex) => {
            console.log(ex);
        });
    }

    handleInputChange = (type, e) => {
        this.query[type] = e.target.value;
    }

    handleCityChange = (e) => {
        if (e[1]) {
            this.query["city"] = e[1];
        } else {
            this.query["city"] = "";
        }
    }

    handleSelectChange = (type, e) => {
        if (e === "-1") {
            this.query[type] = null;
        } else {
            this.query[type] = e;
        }

    }

    handleExport = () => {
        let excelUrl = prefixFile + '/export.do?serviceName=workOrder&fileName=工单管理&searchJson=';
        let paramUrl = '{';
        Object.keys(this.query).map((key) => {
            if (this.query[key]) {
                paramUrl += `"${key}"` + ":" + `"${this.query[key]}"` + ","
            }
        });
        if (paramUrl.length > 0) {
            paramUrl = paramUrl.substr(0, paramUrl.length - 1)
        }
        paramUrl += "}";
        window.location.href = excelUrl + paramUrl;
    }

    handleCreateDatePickerChange=(dates) => {
        const startDate = dates[0];
        const endDate = dates[1];

        if (!startDate || !endDate) {
            this.query.createStartDate = null;
            this.query.createEndDate = null;
            this.setState({
                createDateRangeValue: null
            });
            return;
        }

        this.query.createStartDate = startDate.format("YYYY-MM-DD");
        this.query.createEndDate = endDate.format("YYYY-MM-DD");
        this.setState({
            createDateRangeValue: dates
        });
    }

    handleFinishDatePickerChange=(dates) => {
        const startDate = dates[0];
        const endDate = dates[1];

        if (!startDate || !endDate) {
            this.query.finishStartDate = null;
            this.query.finishEndDate = null;
            this.setState({
                finishDateRangeValue: null
            });
            return;
        }

        this.query.finishStartDate = startDate.format("YYYY-MM-DD");
        this.query.finishEndDate = endDate.format("YYYY-MM-DD");
        this.setState({
            finishDateRangeValue: dates
        });
    }

    handleReturnVisitModalCancel=() => {
        this.setState({
            returnVisitModalVisible: false,
            isInitValue: true
        })
    }

    handleReturnVisit=(params) => {
        this.returnVisitParams = params;
    }

    handleReturnVisitModalOk=() => {
        this.returnVisitParams.id = this.currentRecordId;
        this.setState({
            rvConfirmLoading: true
        })
        returnVisit(this.returnVisitParams).then((res) => {
            if (!res) {
                return;
            }
            if (res.data.code === "200") {
                message.success("操作成功！")
            }
            this.setState({
                returnVisitModalVisible: false,
                isInitValue: true,
                rvConfirmLoading: false
            })
        })
    }

    openTab(param, e) {
        this.props.onAdd.bind(window.LayoutTab)(e, param);
    }

    render() {
        const Content = <div className="sc-page-content">
            <div className="page-toolbar">
                <Row gutter={8}>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="电桩编号精确查询" onChange={(e) => this.handleInputChange("stubNo", e)}/>
                    </Col>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="电站名称查询" onChange={(e) => this.handleInputChange("stubGroupName", e)}/>
                    </Col>
                    <Col lg={3} xl={3}>
                        <AreaPicker pickAreaHandler={this.handleCityChange}/>
                    </Col>
                    <Col lg={3} xl={3}>
                    	<Input placeholder="故障代码" onChange={(e) => this.handleInputChange("faultCodeStr", e)}/>
                        { /*<Select placeholder="故障代码">
                        	
                        </Select>*/ }
                    </Col>
                    <Col lg={3} xl={3}>
                        <Select onChange={(e) => this.handleSelectChange("faultType", e)} placeholder="故障类别" >
                            <Option value="-1">全部</Option>
                            {this.state.typeOptions}
                        </Select>
                    </Col>
                    <Col lg={3} xl={3}>
                        <Input placeholder="故障描述" onChange={(e) => this.handleInputChange("faultDesc", e)}/>
                    </Col>
                    <Col lg={3} xl={3}>
                        <Select onChange={(e) => this.handleSelectChange("workOrderStatus", e)} placeholder="工单状态" >
                            <Option value="-1">全部</Option>
                            {this.state.statusOptions}
                        </Select>
                    </Col>
                </Row>
                <Row gutter={8} className={'work-order'}>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="报修人" onChange={(e) => this.handleInputChange("userName", e)}/>
                    </Col>
                    <Col lg={3} xl={3} className="whole-fill">
                        <Input placeholder="联系电话" onChange={(e) => this.handleInputChange("userPhone", e)} />
                    </Col>
                    <Col lg={3} xl={3}>
                        <Select onChange={(e) => this.handleSelectChange("cs", e)} placeholder="客服" >
                            <Option value="-1">全部</Option>
                            {this.state.csOptions}
                        </Select>
                    </Col>
                    <Col lg={3} xl={3}>
                        <Select onChange={(e) => this.handleSelectChange("repairMan", e)} placeholder="维修人" >
                            <Option value="-1">全部</Option>
                            {this.state.repairManOptions}
                        </Select>
                    </Col>
					<Col lg={6} xl={6}>
                    	<RangePicker format="YYYY-MM-DD" value={this.state.createDateRangeValue} placeholder={['上报开始日期', '上报结束日期']} locale={locale} onChange={this.handleCreateDatePickerChange} />
                    </Col>
                    <Col lg={6} xl={6}>
                    	<RangePicker format="YYYY-MM-DD" value={this.state.finishDateRangeValue} placeholder={['完结开始日期', '完结结束日期']} locale={locale} onChange={this.handleFinishDatePickerChange} />
                    </Col>
                    
                </Row>
				<div className={'button-row'}>
					<Button type="primary" onClick={this.queryHandler}>查询</Button>

					<Button type="primary" onClick={() => this.openTab({},{
						'key': 'addWorkOrder',
						titleText: '新建工单'})}>新建工单</Button>

					<Button type="primary" onClick={this.handleExport}>导出</Button>
                </div>


            </div>
            <div className="page-panel">
                <GridTable postyle="table-center" data={this.state.data} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
            </div>
            <Modal width="800px" title={'回访'} visible={this.state.returnVisitModalVisible} confirmLoading={this.state.rvConfirmLoading} onOk={this.handleReturnVisitModalOk} onCancel={this.handleReturnVisitModalCancel}>
            	<ReturnVisit record={this.state.record} handle={this.handleReturnVisit} isInitValue={this.state.isInitValue}/>
            </Modal>
        </div>;

        return Content;
    }

}

export default ManageWorkOrder;